/*
 * Copyright (c) 2000-2015 Tacke Consulting, Inc
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 * of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE.
 * 
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
//using OpenNETCF.Configuration;

namespace OpenNETCF.Media
{
    #region Debug Logger
    /// <summary>
    /// Debug logger class for debugging any errors during playback
    /// </summary>
    internal class DebugLogger
    {
        string m_name = "";
        string m_indent = "";
        bool m_timestamps = false;
        bool m_startLine = true;
        string m_errorPrefix = "ERROR>";

        private object m_syncRoot = new object();
        private static string m_path;
        private static object m_pathSyncRoot = new object();

        private bool m_debugEnabled = false;

        public DebugLogger(string fileName)
            : this(fileName, false, true)
        {
        }

        public DebugLogger(string fileName, bool timestamps, bool truncate)
        {
            if (IsDesignTime)
                return;

            m_debugEnabled = MediaPlayerConfig.DebugModeEnabled;

            if (!m_debugEnabled)
                return;

            m_timestamps = timestamps;
            m_name = fileName;

            if (truncate)
            {
                if (File.Exists(m_name))
                {
                    try
                    {
                        File.Delete(m_name);
                    }
                    catch {/*ignore delete exceptions*/ }
                }
            }
        }

        private string DebugPath(string filename)
        {

            lock (m_pathSyncRoot)
            {
                if (m_path == null)
                {
                    m_path = Path.Combine(@"\Logs", DateTime.Now.ToString("MM-dd-yyyy-HH.mm.ss"));
                    if (!Directory.Exists(m_path))
                        Directory.CreateDirectory(m_path);
                }
                return Path.Combine(m_path, Path.GetFileName(filename));
            }
        }

        public bool TimeStamps
        {
            set { m_timestamps = value; }
            get { return m_timestamps; }
        }

        public string ErrorPrefix
        {
            set { m_errorPrefix = value; }
            get { return m_errorPrefix; }
        }

        public void Indent()
        {
            if (!m_debugEnabled)
                return;

            m_indent += "  ";
        }

        public void Unindent()
        {
            if (!m_debugEnabled)
                return;

            int length = m_indent.Length;
            if (length < 2)
            {
                return;
            }
            if (length == 2)
            {
                m_indent = "";
            }
            m_indent = new string(' ', length - 2);
        }

        public void WriteLine(object obj)
        {
            if (!m_debugEnabled)
                return;

            WriteLine(obj.ToString());
        }

        public void WriteLine(string text, bool suppressTimestamp)
        {
            if (!m_debugEnabled)
                return;

            bool oldTimestamp = TimeStamps;
            TimeStamps = false;
            WriteLine(text);
            TimeStamps = oldTimestamp;
        }

        public void WriteLine(string text)
        {
            if (!m_debugEnabled)
                return;

            Write(text + "\r\n");
            m_startLine = true;
        }

        public void WriteError(string text)
        {
            if (!m_debugEnabled)
                return;

            WriteLine(string.Format("{0}{1}", ErrorPrefix, text));
        }

        public void WriteException(string text, Exception e)
        {
            if (!m_debugEnabled)
                return;

            WriteLine(string.Format("{0}{1} : {2}\r\n{3}", ErrorPrefix, text, e.Message, e.StackTrace));
        }

        public void Write(string text)
        {
            if (!m_debugEnabled)
                return;

            lock (m_syncRoot)
            {
                TextWriter writer;
                try
                {
                    writer = File.AppendText(m_name);
                }
                catch (Exception)
                {
                    // unable to open, so just bail out
                    goto done;
                }
                try
                {
                    if (m_timestamps && m_startLine)
                    {
                        writer.Write(string.Format("{0:X8}: {1}{2}", Environment.TickCount, m_indent, text));
                        Debug.Write(string.Format("{0:X8}: {1}{2}", Environment.TickCount, m_indent, text));
                    }
                    else
                    {
                        writer.Write(string.Format("{0}{1}", m_indent, text));
                        Debug.Write(string.Format("{0}{1}", m_indent, text));
                    }
                }
                catch { }

                writer.Close();
            done: ;
            }
            m_startLine = false;
        }

        private bool m_isDesignTimeChecked;
        private bool m_isDesignTime;
        internal bool IsDesignTime
        {
            get
            {
                if (!m_isDesignTimeChecked)
                {
                    try
                    {
                        // Determine if this instance is running against .NET Framework by using the MSCoreLib PublicKeyToken
                        System.Reflection.Assembly mscorlibAssembly = typeof(int).Assembly;
                        if ((mscorlibAssembly != null))
                        {
                            if (mscorlibAssembly.FullName.ToUpper().EndsWith("B77A5C561934E089"))
                            {
                                m_isDesignTime = true;
                            }
                            else
                            {
                                m_isDesignTime = false;
                            }
                        }
                    }
                    finally
                    {
                        m_isDesignTimeChecked = true;
                    }
                }

                return m_isDesignTime;
            }
        }
    }

    
        
    #endregion
}
